package com.peng._05weibo.controller;

import com.peng._05weibo.common.response.JsonResult;
import com.peng._05weibo.common.response.StatusCode;
import com.peng._05weibo.mapper.WeiboMapper;
import com.peng._05weibo.pojo.dto.WeiboDTO;
import com.peng._05weibo.pojo.entity.Weibo;
import com.peng._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 微博控制器
 *
 * @Author peng
 * @Date 2024-04-23 11:37
 */
@RestController
@RequestMapping("/v1/weibo")
@Slf4j
@Validated
@Api(tags = "微博模块")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    /**
     * 发布微博
     *
     * @param weiboDTO 发布微博DTO
     * @param session  用户session
     * @return 1-成功 2-用户未登录
     */
    @ApiOperation("发布微博")
    @PostMapping("/insert")
    public JsonResult publishWeibo(@RequestBody WeiboDTO weiboDTO, HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
//        if (userVO == null) {
//            System.out.println("用户未登录");
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Weibo weibo = Weibo.builder()
                .content(weiboDTO.getContent())
                .userId(userVO.getId())
                .created(new Date())
                .build();
        weiboMapper.insertWeibo(weibo);
        return JsonResult.success("发布成功");
    }

    /**
     * 获取微博详情页面
     *
     * @return 微博列表
     */
    @ApiOperation("获取微博列表")
    @GetMapping("/selectIndex")
    public JsonResult getWeiboIndex() {
        return JsonResult.success("获取成功", weiboMapper.selectAllWeibo());
    }

    /**
     * 根据微博id获取微博详情
     *
     * @param id 微博id
     * @return 微博详情
     */
    @ApiOperation("根据微博id获取微博详情")
    @ApiImplicitParam(name = "id", value = "微博id", required = true, dataType = "Long")
    @GetMapping("/selectById")
    public JsonResult getWeiboDetail(@Range(min = 200, max = 300, message = "微博ID在200~300之间") @RequestParam Long id) {
        if (id<0){
            throw new IllegalArgumentException("微博id不能为负数");
        }
        return JsonResult.success("获取微博详情成功", weiboMapper.getWeiboDetailById(id));
    }
}

